﻿using Newtonsoft.Json;
using Orleans;
using Pay.Cache;
using Pay.Container;
using Pay.Core.exception;
using Pay.Core.http;
using Pay.Dal;
using Pay.Model;
using Pay.Model.Dto;
using Pay.Model.Model;
using Pay.Service;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;

namespace Pay.Api.Controllers
{


    [RoutePrefix("api/aliService")]
    public class AliOperateController : BaseController
    {
        /// <summary>
        /// 接受订单数据
        /// </summary>
        /// <param name="Orders"></param>
        /// <returns></returns>
        [Route("OrderRecord"), HttpPost]
        public async Task<IHttpActionResult> AcceptAliInfo([FromBody]List<AliOrderInput> Orders)
        {

            try
            {
                if (Orders != null && Orders.Any())
                {

                    //存入redis
                    var nameSpace = "payService:" + Orders[0].SystemAccount;
                    RedisHelper helper = new RedisHelper();
                    var list = helper.ListRange<AliOrderInput>(nameSpace);
                    if (list == null || list.Count == 0)
                    {
                        for (int i = 0; i < Orders.Count; i++)
                        {
                            helper.ListLeftPush<AliOrderInput>(nameSpace, Orders[i]);
                        }
                        //塞入数据库
                        foreach (var item in Orders)
                        {

                            //插入数据库
                            var service = GrainClient.GrainFactory.GetGrain<IAliOrderService>(item.SystemAccount);
                            var info = new AliOrderInfo()
                            {
                                AliOrderNo = item.OrderNo,
                                Amount = item.Amount,
                                CreateTime =Convert.ToDateTime(item.CreateTime),
                                SysTime = DateTime.Now,
                                Des = item.Des,
                                Status = item.Status
                            };
                            await service.Add(info);

                        }
                    }
                    else
                    {
                        var allData = helper.ListRange<AliOrderInput>(nameSpace);
                        //获取list长度

                        foreach (var item in Orders)
                        {
                            var temp = allData.Where(c => c.OrderNo == item.OrderNo).FirstOrDefault();
                            if (temp == null)
                            {
                                var length = helper.ListLength(nameSpace);
                                if (length >= 100)
                                {
                                    helper.ListRightPop<AliOrderInput>(nameSpace);
                                }

                                helper.ListLeftPush<AliOrderInput>(nameSpace, item);

                                //插入数据库
                                var service = GrainClient.GrainFactory.GetGrain<IAliOrderService>(item.SystemAccount);
                                var info = new AliOrderInfo()
                                {
                                    AliOrderNo = item.OrderNo,
                                    Amount = item.Amount,
                                    CreateTime = Convert.ToDateTime(item.CreateTime),
                                    SysTime = DateTime.Now,
                                    Des = item.Des,
                                    Status = item.Status
                                };
                                await service.Add(info);
                            }
                        }
                    }

                    return Ok(new { success = true, msg = "传入成功" });
                }
                else
                {
                    return Ok(new { success = false, msg = "传入数据为空" });
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }

        }

        /// <summary>*
        /// 根据系统账号获取支付宝账号和密码
        /// </summary>
        /// <param name="systemName"></param>
        /// <returns></returns>
        [Route("Accountinfo/{systemName}"), HttpGet]
        public async Task<AccountInfoOut> GetAliAccountInfo([FromUri] string systemName)
        {
           
            var service = GrainClient.GrainFactory.GetGrain<IAliaccountService>("0");
            var info = await service.GetInfoBySystemName(systemName);
            var res = new AccountInfoOut();
            if (info != null)
            {
                res.Account = info.AccountName;
                res.Pwd = info.Pwd;
            }
            return res;
        }
        
        /// <summary>
        /// 查询订单 调用异步地址
        /// </summary>
        private void FindOrder(decimal amount, string des, long orderId, string callBack)
        {
            //查询order

            ThreadPool.QueueUserWorkItem((c) =>
            {
                while (true)
                {
                    var instance = LocManager.Resolve<IAliOrderDal>();

                    var task = instance.GetOrder(amount, des);
                    task.Wait();
                    var res = task.Result;
                    if (res == null)
                    {
                        Thread.Sleep(1000);
                    }
                    else
                    {
                        //更新订单状态
                        var orderInstance = LocManager.Resolve<IOrderDal>();
                        var orderTask = orderInstance.GetById(orderId);
                        orderTask.Wait();
                        var model = orderTask.Result;

                        // model.Status = Model.Enums.AlipayOrderStatus.Paid;
                        var Updatetask = orderInstance.Update(model);
                        Updatetask.Wait();
                        //发送请求
                        var json = JsonConvert.SerializeObject(new PayOut { Msg = "支付成功", Success = true });
                        string resMsg = string.Empty;
                        HttpHelper.SendAndGet(callBack, json, "application/json", ref resMsg);

                        break;
                    }
                }
            });
        }

        private int CreateRand(int max)
        {
            Random r = new Random();
            return r.Next(0, max + 1);
        }
        /// <summary>
        /// 更新支付宝账号间隔时间
        /// </summary>
        /// <param name="timeCount"></param>
        /// <returns></returns>
        [Route("updatetime"), HttpPost]
        public async Task<PayOut> UpdateAccountTime(UpdateTimeModel model)
        {
            var service = GrainClient.GrainFactory.GetGrain<IAliaccountService>("0");
            var info = await service.GetInfoBySystemName(model.systemName);
            if (info == null) throw new LotException("没有对应支付宝账号");
            info.ActiveTime = DateTime.Now;
            dynamic ctx = Request.Properties["MS_HttpContext"];
            if (ctx != null)
            {
                info.IpAddress = ctx.Request.UserHostAddress;
            }
            await service.Update(info);
            return new PayOut() { Msg = "更新成功", Success = true };
        }
    }

    public class UpdateTimeModel
    {
        public string systemName { get; set; }
        public int timeCount { get; set; }
    }

    public class AccountInfoOut
    {
        public string Account { get; set; }

        public string Pwd { get; set; }
    }

    public class AliOrderInputs
    {
        public List<AliOrderInput> Input { get; set; }
    }
}
